package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
   @Autowired
   FileStorageService fileStorageService;
   @Value("${file.oss.prefix}")
   String prefix;
   @Value("${file.oss.web-site}")
   String website;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //1.检查参数
        if (multipartFile==null || multipartFile.getSize()==0) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"您上传的内容为空！");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NEED_ADMIND,"请您先登录！！！");
        }

        //2.获取文件的原始名称
        String originalFilename = multipartFile.getOriginalFilename();
        //3.校验完格式后将该文件上传到OSS中
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //新文件的名称：随机生成的UUID+后缀
        String fileName=uuid+suffix;
        //4.开始上传（注意：文件上传的接口：FileStorageService）
        try {
            //表示文件在OSS中的全路径
            String store = fileStorageService.store(prefix, fileName, multipartFile.getInputStream());
            //创建WmMaterial实体类
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setIsCollection((short)0);
            wmMaterial.setType((short)0);
            wmMaterial.setCreatedTime(new Date());
            // 设置文件id
            wmMaterial.setUrl(store);//需要上传的文件在OSS中路径
            wmMaterial.setUserId(user.getId());//登录用户的id
            //保存素材
            save(wmMaterial);
            //返回结果需要在url上添加访问前缀（主要是用于前端回显图片）
            wmMaterial.setUrl(website+store);
            //将素材进行返回操作
            return ResponseResult.okResult(wmMaterial);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("上传文件失败===》{}",e.getMessage());
          throw new CustomException(AppHttpCodeEnum.SERVER_ERROR,"上传素材失败！");
        }
    }

    @Override
    public ResponseResult findList(WmMaterialDto wmMaterialDto) {
        //检查参数
        wmMaterialDto.checkParam();
        //1.参数校验
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NEED_ADMIND,"请您先登录！");
        }
        //2.封装查询参数
         //2.1分页参数
        Page<WmMaterial> page = new Page(wmMaterialDto.getPage(), wmMaterialDto.getSize());
         //2.2查询参数(查询条件)
        LambdaQueryWrapper<WmMaterial> queryWrapper = Wrappers.lambdaQuery();
        if (wmMaterialDto.getIsCollection()!=null && wmMaterialDto.getIsCollection().intValue()==1){
            queryWrapper.eq(WmMaterial::getIsCollection,1);
        }
        queryWrapper.eq(WmMaterial::getUserId,user.getId());
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        //2.3开始执行查询
        IPage<WmMaterial> page1 = this.page(page, queryWrapper);//将页面的框架和数据传进去
        //2.4封装数据并将结果返回给前端
        PageResponseResult responseResult = new PageResponseResult(wmMaterialDto.getPage(), wmMaterialDto.getSize(), page1.getTotal());
        List<WmMaterial> records = page1.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(website+record.getUrl());
        }
        responseResult.setData(records);
        return responseResult;


    }
    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult delPicture(Integer id) {
//        //1.检查id的值是否为空值，如果为空则判断参数无效
//        if (id==null) {
//            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
//        }
//        //2.创建出查询选择器
//        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(WmNewsMaterial::getMaterialId,id);
        //1.检查id
        if (id==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询改素材是否被引用
        Integer count = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if (count>0) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"此素材已经被引用，不能被删除");
        }
        //3.查询素材信息（OSS路径===删除素材信息必须先把OSS中的路径先删除）
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //4.删除对应的OSS文件
        fileStorageService.delete(wmMaterial.getUrl());
        //5.删除素材的数据
        removeById(id);
        return ResponseResult.okResult();


    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //1.检查参数（要想进行收藏或取消收藏必须为登录状态）
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NEED_ADMIND,"您尚未登录，请登录！");
        }
        //2.通用做法是一查一改（先将从前端传过来对应id的素材的对象查出来，再修改其状态即可）
        //2.1此处采用Mybatisplus的另外一种API(当你只想修改一个对象的某一个字段时)
        update(Wrappers.<WmMaterial>lambdaUpdate()
                          .set(WmMaterial::getIsCollection,type)
                          .eq(WmMaterial::getId,id)
                          .eq(WmMaterial::getUserId,user.getId())
        );
        return ResponseResult.okResult();

    }
}
